import React, { Component } from 'react'
import './mockData'
import store from '@/store'
import { addItemAction, deleteItemAction, inputAction, getMyListAction } from '../../store/actionCreators'
import TodoListUI from './ToDoListUI'
export default class ToDoList extends Component {
  constructor(props) {
    super(props)
    this.state = store.getState()
    this.storeChange = this.storeChange.bind(this)  //转变this指向
    store.subscribe(this.storeChange) //订阅Redux的状态
  }
  // componentWillMount() {
  //   console.log('componentWillMount---组件将要挂载到页面的时候执行')
  // }
  // shouldComponentUpdate(nextProp, nextState) {
  //   // console.log('shouldComponentUpdate---组件发生改变前执行', nextProp, nextState)
  //   return true
  // }
  // componentWillUpdate() {
  //   // console.log('componentWillUpdate---组件更新前，在shouldComponentUpdate函数之后执行')
  // }

  render() {
    return (
      <TodoListUI
        inputValue={this.state.inputValue}
        newList={this.state.newList}
        inputChange={this.inputChange.bind(this)}
        addValue={this.addValue.bind(this)}
        editValue={this.editValue.bind(this)}
        deValue={this.deValue.bind(this)}
        placeholder={store.getState().placeholder}
      ></TodoListUI>
    )
  }
  // componentDidUpdate() {
  //   // console.log('componentDidUpdate---组件更新之后执行')
  // }

  componentDidMount() {
    // console.log('componentDidMount---组件挂载完成的时候执行')
    const action = getMyListAction()
    store.dispatch(action)
  }

  inputChange(e) {
    const action = inputAction(e.target.value)
    store.dispatch(action)
  }
  storeChange() {
    this.setState(store.getState())
  }
  addValue() {
    const action = addItemAction(this.getKey())
    store.dispatch(action)
  }
  deValue(k) {
    const action = deleteItemAction(k)
    store.dispatch(action)
  }
  editValue(k, v) {
    let newList = this.state.newList
    newList[k].val = v
    this.setState({
      newList: newList
    })
  }

  getKey() {
    return new Date().getTime() + Math.random()
  }
}
